//
//  DKHttpHelper.m
//  DanKU
//
//  Created by 吴斌 on 2023/10/1.
//

#import "DKHttpHelper.h"
#import <AFNetworking/AFNetworking.h>
#import "DKLoginViewController.h"
#import "CustomLogger.h"
@interface DKHttpHelper()
@property (strong, nonatomic) AFHTTPSessionManager *manager;
@end
@implementation DKHttpHelper
static DKHttpHelper *defaultManager = nil;
+ (instancetype)request{
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        if(defaultManager == nil){
            defaultManager = [[DKHttpHelper alloc] init];
        }
    });
    return defaultManager;
}
- (instancetype)init{
  if(self = [super init]){
      self.manager = [AFHTTPSessionManager manager];
      self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
      self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
//      [self.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
      self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"multipart/form-data", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
      self.manager.requestSerializer.timeoutInterval = 10.0;
  }
  return self;
}
- (NSDictionary *)getHttpHead{
    NSMutableDictionary * dk_httpHeadDic = [[NSMutableDictionary alloc] init];
    [dk_httpHeadDic setValue:[NSString getAppVersion] forKey:@"x-version"];
    [dk_httpHeadDic setValue:DK_PackageName forKey:@"x-package-name"];
    [dk_httpHeadDic setValue:DK_AppName forKey:@"x-app-name"];
    
    DKRegisterUserModel * dkRegisterUserMdl = [DKGlobalHelper getRegisterUserInfo];
    if(DK_ObjectNil(dkRegisterUserMdl.token)){
        [dk_httpHeadDic setValue:@"" forKey:@"x-auth-token"];
    }else{
        [dk_httpHeadDic setValue:dkRegisterUserMdl.token forKey:@"x-auth-token"];
    }
    return dk_httpHeadDic.copy;
}
- (void)GET:(NSString *)url params:(nullable id)params withJson:(BOOL)isRequestJson withIsLoad:(BOOL)isLoad success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler{
    NSLog(@"Get地址:%@",url);
    NSLog(@"Get参数:%@",params);
    WeakSelf(self)
    if(isLoad){
        [SVProgressHUD show];
    }
    if(isRequestJson){
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else{
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    [self.manager GET:url parameters:params headers:[self getHttpHead] progress:^(NSProgress * _Nonnull downloadProgress) {
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"返回值:%@\n%@",url,responseObject);
        [weakSelf successWithTask:task responseObject:responseObject withUrl:url params:params successHandler:successHandler failureHandler:failureHandler];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"返回值:%@\n%@",url,error);
        [weakSelf failureWithTask:task withUrl:url error:error failureHandler:failureHandler];
    }];
}
- (void)POST:(NSString *)url params:(nullable id)params withJson:(BOOL)isRequestJson withIsLoad:(BOOL)isLoad success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler{
    NSLog(@"Post地址:%@",url);
    NSLog(@"Post参数:%@",params);
    WeakSelf(self)
    if(isLoad){
        [SVProgressHUD show];
    }
    if(isRequestJson){
        self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else{
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    [self.manager POST:url parameters:params headers:[self getHttpHead] progress:^(NSProgress * _Nonnull uploadProgress) {
                    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [weakSelf successWithTask:task responseObject:responseObject withUrl:url params:params successHandler:successHandler failureHandler:failureHandler];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"返回值:%@\n%@",url,error);
        [weakSelf failureWithTask:task withUrl:url error:error failureHandler:failureHandler];
    }];
}
- (void)POST:(NSString *)url params:(nullable id)params withData:(NSData *)fileData success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler{
    NSLog(@"Post地址:%@",url);
    NSLog(@"Post参数:%@",params);
    WeakSelf(self)
    [SVProgressHUD show];
    self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",nil];
//    NSString *boundary = @"dasjndasxnxaskmasxkj";
    self.manager.requestSerializer.timeoutInterval = 60.0;
    [self.manager.requestSerializer setValue:@"multipart/form-data;boundary=dasjndasxnxaskmasxkj" forHTTPHeaderField: @"Content-Type"];
    [self.manager POST:url parameters:params headers:[self getHttpHead] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        [formData appendPartWithFileData:fileData name:@"photo" fileName:fileName mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [weakSelf successWithTask:task responseObject:responseObject withUrl:url params:params successHandler:successHandler failureHandler:failureHandler];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"返回值:%@\n%@",url,error);
        [weakSelf failureWithTask:task withUrl:url error:error failureHandler:failureHandler];
    }];
}
//不用加载
- (void)POST:(NSString *)url params:(nullable id)params withData:(NSData *)fileData withLoad:(BOOL)isLoad success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler{
    NSLog(@"Post地址:%@",url);
    NSLog(@"Post参数:%@",params);
    WeakSelf(self)
    if(isLoad){
        [SVProgressHUD show];
    }
    self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",nil];
//    NSString *boundary = @"dasjndasxnxaskmasxkj";
    self.manager.requestSerializer.timeoutInterval = 60.0;
    [self.manager.requestSerializer setValue:@"multipart/form-data;boundary=dasjndasxnxaskmasxkj" forHTTPHeaderField: @"Content-Type"];
    [self.manager POST:url parameters:params headers:[self getHttpHead] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        [formData appendPartWithFileData:fileData name:@"photo" fileName:fileName mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [weakSelf successWithTask:task responseObject:responseObject withUrl:url params:params successHandler:successHandler failureHandler:failureHandler];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"返回值:%@\n%@",url,error);
        [weakSelf failureWithTask:task withUrl:url error:error failureHandler:failureHandler];
    }];
}
#pragma mark - 成功处理
- (void)successWithTask:(NSURLSessionDataTask *)task responseObject:(id)responseObject withUrl:(NSString *)url params:(nullable id)params successHandler:(requestSuccessBlock)successHandler failureHandler:(requestFailureBlock)failureHandler {
    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)task.response;
    NSInteger statusCode = resp.statusCode;
    NSString *contentType = resp.allHeaderFields[@"Content-Type"];
    if ([contentType containsString:@"json"]) {
        NSDictionary *jsonDict = nil;
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            jsonDict = responseObject;
        }else {
            jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        }
        CustomLog(@"返回值:%@\n%@",url,jsonDict);
        if([[jsonDict valueForKey:@"code"] isEqualToString:@"-1"]){
            NSString * errorMsg = [jsonDict valueForKey:@"message"];
            [DKAlertHelper showMessage:errorMsg];
            //返回登录页面
            DKLoginViewController * dk_LoginViewCtrl = [[DKLoginViewController alloc] init];
            UINavigationController *dk_LoginViewNavCtrl = [[UINavigationController alloc] initWithRootViewController:dk_LoginViewCtrl];
            ((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController = dk_LoginViewNavCtrl;
            [DKGlobalHelper loginOutApp];
        }else if ([[jsonDict valueForKey:@"code"] isEqualToString:@"500"]){
            [DKAlertHelper showMessage:@"The system is experiencing problems, please try again later"];
        }else if([[jsonDict valueForKey:@"code"] intValue] == 200){//返回成功
            successHandler(statusCode, jsonDict);
        }else{
//            if([url isEqualToString:[NSString getServiceUrl:DK_AuthCommonUploadPanPositive]]||([url isEqualToString:[NSString getServiceUrl:DK_AuthSaveUserInfo]]&&[[params objectForKey:@"step"] isEqualToString:@"IDENTITY_INFO"])){
//                NSString * errorMsg = [jsonDict valueForKey:@"message"];
//                failureHandler(statusCode,errorMsg);
//            }else{
            if([url isEqualToString:[NSString getServiceUrl:DK_AuthCommonUploadPanPositive]]){
               NSString * errorMsg = [jsonDict valueForKey:@"message"];
               failureHandler(statusCode,errorMsg);
            }else if([url isEqualToString:[NSString getServiceUrl:DK_AuthSaveUserInfo]]&&[[params objectForKey:@"step"] isEqualToString:@"IDENTITY_INFO"]){
                NSString * errorMsg = [jsonDict valueForKey:@"message"];
                [DKAlertHelper showPopupMessage:errorMsg toView:[UIApplication sharedApplication].delegate.window centerPoint:CGPointMake([UIApplication sharedApplication].delegate.window.center.x, [UIApplication sharedApplication].delegate.window.center.y + DK_IsWidthScale(80))];
                failureHandler(statusCode,errorMsg);
             }else{
                NSString * errorMsg = [jsonDict valueForKey:@"message"];
                failureHandler(statusCode,errorMsg);
                [DKAlertHelper showMessage:errorMsg];
            }
        }
    } else {
        [DKAlertHelper showMessage:@"error"];
    }
    [SVProgressHUD dismiss];
}

#pragma mark - 失败处理
- (void)failureWithTask:(NSURLSessionDataTask *)task withUrl:(NSString *)url error:(NSError *)error failureHandler:(requestFailureBlock)failureHandler {
    if(![url isEqualToString:[NSString getServiceUrl:DK_UserRsaKey]]){
        [DKAlertHelper showMessage:@"Oops, connecting to the server failed"];
    }
    [SVProgressHUD dismiss];
    failureHandler(0,@"");
}
@end
